package controllers

import (
    "gouniapp/configs"
	"net/http"
	"time"
	"encoding/json"
	"gorm.io/datatypes"
	"github.com/gin-gonic/gin"
)

// 获取唯一模板（前端只需要调用这个接口）
func GetHomeTemplate(c *gin.Context) {
	var template configs.HomeTemplate
	if err := configs.DB.First(&template).Error; err != nil {
		// 如果不存在则创建默认模板
		defaultTemplate := configs.HomeTemplate{
			Name:            "默认模板",
			BackgroundColor: "#ffffff",
			PagePadding:     16,
			IsEnabled:       false,
			Components:      datatypes.JSON("[]"),
		}
		if createErr := configs.DB.Create(&defaultTemplate).Error; createErr != nil {
			JsonResponse(c, http.StatusInternalServerError, "初始化模板失败", nil)
			return
		}
		template = defaultTemplate
	}
	JsonResponse(c, http.StatusOK, "获取成功", template)
}

// 保存/更新模板（合并创建和更新）
func SaveHomeTemplate(c *gin.Context) {
	var req struct {
		Name            string                   `json:"name"`
		BackgroundColor string                   `json:"backgroundColor"`
		PagePadding     int                      `json:"pagePadding"`
		Components      []map[string]interface{} `json:"components"`
		IsEnabled       bool                     `json:"is_enabled"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		JsonResponse(c, http.StatusBadRequest, "参数错误", nil)
		return
	}

	// 序列化组件配置
	componentsJSON, err := json.Marshal(req.Components)
	if err != nil {
		JsonResponse(c, http.StatusInternalServerError, "组件序列化失败", nil)
		return
	}

	// 始终只保留一个模板
	var existing configs.HomeTemplate
	if err := configs.DB.First(&existing).Error; err == nil {
		// 更新现有模板
		updates := map[string]interface{}{
			"name":             req.Name,
			"background_color": req.BackgroundColor,
			"page_padding":     req.PagePadding,
			"is_enabled":        req.IsEnabled,
			"components":       componentsJSON,
			"updated_at":       time.Now(),
		}
		if err := configs.DB.Model(&existing).Updates(updates).Error; err != nil {
			JsonResponse(c, http.StatusInternalServerError, "更新失败", nil)
			return
		}
	} else {
		// 创建新模板（理论上不会执行到这里）
		newTemplate := configs.HomeTemplate{
			Name:            req.Name,
			BackgroundColor: req.BackgroundColor,
			PagePadding:     req.PagePadding,
			Components:      componentsJSON,
			IsEnabled:       req.IsEnabled,
		}
		if err := configs.DB.Create(&newTemplate).Error; err != nil {
			JsonResponse(c, http.StatusInternalServerError, "创建失败", nil)
			return
		}
	}

	JsonResponse(c, http.StatusOK, "保存成功", nil)
}